package com.atguigu.gmall.utils;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.user.vo.UserAuthInfoVo;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UserAuthUtils {
    public static UserAuthInfoVo getUserAuthInfo() {
        UserAuthInfoVo userAuthInfoVo = new UserAuthInfoVo();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        try {
            request = requestAttributes.getRequest();
        } catch (Exception e) {
        }
        String userTempId = request.getHeader(RedisConst.USER_TEMP_ID_HEADER);
        String userId = request.getHeader(RedisConst.USER_ID_HEADER);
        if (!StringUtils.isEmpty(userId)){
            userAuthInfoVo.setUserId(Long.valueOf(userId));
        }
        userAuthInfoVo.setUserTempId(userTempId);
        return userAuthInfoVo;
    }

    public static Long getUserId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String userId = request.getHeader(RedisConst.USER_ID_HEADER);
        if (StringUtils.isEmpty(userId)){
            return null;
        }
        return Long.valueOf(userId);
    }
}
